// =====================addmenuplus 配置 runningcheese 版======================

// =====================右键菜单定制======================
//复制所选
page([{label:'复制',id:"context-copy",condition:"select",accesskey:"",clone:false},{label:'粘贴所选',id:"context-paste",condition:"input",accesskey:"",clone:false},{label:'剪切所选',id:"context-cut",condition:"input",accesskey:"",clone:false},{label: '删除所选',id: "context-delete",condition:"input",accesskey:"",clone:false}]);



// 页面信息右键菜单
new function () {
	var items = [
{
label : "置顶当前窗口",
id:"context_StickyTab",
onclick : function () {
	(function ()
{if(document.getElementById('main-window').hasAttribute('ontop'))
onTop=false;else onTop=true;
	try {

	Components.utils.import("resource://gre/modules/ctypes.jsm");
	var lib = ctypes.open("user32.dll");
	var funcActiveWindow = 0;
	try
	{
		 funcActiveWindow = lib.declare("GetActiveWindow", ctypes.winapi_abi, ctypes.int32_t);
	}
	catch (ex)
	{
		funcActiveWindow = lib.declare("GetActiveWindow", ctypes.stdcall_abi, ctypes.int32_t);
	}
	
	if (funcActiveWindow != 0)
	{
		var activeWindow = funcActiveWindow();
		
		var funcSetWindowPos = 0;
		try
		{
			funcSetWindowPos = lib.declare("SetWindowPos",
								ctypes.winapi_abi,
								ctypes.bool,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.uint32_t);
		}
		catch(ex)
		{
			funcSetWindowPos = lib.declare("SetWindowPos",
								ctypes.stdcall_abi,
								ctypes.bool,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.int32_t,
								ctypes.uint32_t);		
		}
		
		var hwndAfter = -2;
		if (onTop)
			{hwndAfter = -1;document.getElementById('main-window').setAttribute('ontop','true');}else document.getElementById('main-window').removeAttribute('ontop');

		funcSetWindowPos(activeWindow, hwndAfter, 0, 0, 0, 0, 19);
	}

	lib.close();
	
	} catch (ex) {
		alwaysontop_log(ex);
	}
})()
},
},
 {
				label : '批量选择操作',
				image :"",
				oncommand:   function() {gBrowser.mPrefs.setBoolPref('extensions.grabanddrag.on',false); snapLinks.init();},
},{
				label : '谷歌站内搜索',
				image :"",
				oncommand :function () {
				gBrowser.loadURI("javascript:var%20Bar=location.host+%22%22;q%20=%20%22%22%20+%20(window.getSelection%20?%20window.getSelection()%20:%20document.getSelection%20?%20document.getSelection()%20:%20document.selection.createRange().text);%20if%20(!q)%20q%20=%20prompt(%22\u8BF7\u8F93\u5165\u641C\u7D22\u7684\u5173\u952E\u8BCD:%22,%20%22%22);%20if%20(q!=null)%20{var%20qlocation=%22%20%22;qlocation=('https://www.google.com/search?num=30&hl=zh-CN&newwindow=1&q='+q+'&sitesearch='+Bar+'');window.open(qlocation);}%20void%200");
				}
},{
				label : '百度站内搜索',
				image :"",
				oncommand :function () {
				gBrowser.loadURI("javascript:var%20Bar=location.host+%22%22;q%20=%20%22%22%20+%20(window.getSelection%20?%20window.getSelection()%20:%20document.getSelection%20?%20document.getSelection()%20:%20document.selection.createRange().text);%20if%20(!q)%20q%20=%20prompt(%22\u8BF7\u8F93\u5165\u641C\u7D22\u7684\u5173\u952E\u8BCD:%22,%20%22%22);%20if%20(q!=null)%20{var%20qlocation=%22%20%22;qlocation=('http://www.baidu.com/s?&ie=UTF-8&oe=UTF-8&cl=3&rn=100&wd=%20%20'+q+'%20%20%20site:%20'+Bar+'');window.open(qlocation);}%20void%200");
				}
},
{
		label: "显示所有地址",
		keyword: 'showl',
		image:""
	},{
		label: "显示所有图片",
		oncommand: function() {
               gBrowser.loadURI("javascript:outText='';for(i=0;i<document.images.length;i++){if(outText.indexOf(document.images%5Bi%5D.src)==-1){outText+='<tr><td><img%20src='+document.images%5Bi%5D.src+'></td><td>'+document.images%5Bi%5D.height+'</td><td>'+document.images%5Bi%5D.width+'</td><td>'+document.images%5Bi%5D.src+'</td></tr>'}};if(outText!=''){imgWindow=window.open('','imgWin','width=800,height=600');imgWindow.document.write%20('<table%20border=1%20cellpadding=10><tr><th>Image</th><th>Height</th><th>Width</th><th>URL</th></tr>'+outText+'</table>');imgWindow.document.close()}else{alert('No%20images!')}");
			   },
		image:""
	},	 	
{
		label: "购物比价工具",
		oncommand: function() {
               gBrowser.loadURI("javascript:(function(){var%20s%20=%20document.createElement('script');s.setAttribute('src','https://browser.gwdang.com/get.js?f=/js/gwdang_extension.js');document.body.appendChild(s);})();");
			   },
		image:""
	},
{
		label:"查看明文密码",
		url: "javascript:(function()%7Bvar%20IN,F;IN=document.getElementsByTagName('input');for(var%20i=0;i<IN.length;i++)%7BF=IN%5Bi%5D;if(F.type.toLowerCase()=='password')%7Btry%7BF.type='text'%7Dcatch(r)%7Bvar%20n,Fa;n=document.createElement('input');Fa=F.attributes;for(var%20ii=0;ii<Fa.length;ii++)%7Bvar%20k,knn,knv;k=Fa%5Bii%5D;knn=k.nodeName;knv=k.nodeValue;if(knn.toLowerCase()!='type')%7Bif(knn!='height'&&knn!='width'&!!knv)n%5Bknn%5D=knv%7D%7D;F.parentNode.replaceChild(n,F)%7D%7D%7D%7D)()",
		image:""
	},

];
	var menu = PageMenu({
		label: "多功能菜单",
		condition: 'normal',
		insertBefore: 'context-openlinkincurrent',
		image:""
	});
	menu(items);
};


//当前页面
new function () {
	var items = [
	{
    label: "编辑当前页面",
    image: "",
    oncommand: function() {document.onkeydown=ck;content.document.body.contentEditable=true;function ck(e){k=window.event?window.event.keyCode:e.keyCode;if(k==27){content.document.body.contentEditable=false}}}
},
{
                label: '解除右键限制',
                image: "",
                oncommand: function() {
                gBrowser.loadURI("javascript:(function(bookmarklets)%7Bfor(var%20i=0;i%3Cbookmarklets.length;i++)%7Bvar%20code=bookmarklets%5Bi%5D.url;if(code.indexOf(%22javascript:%22)!=-1)%7Bcode=code.replace(%22javascript:%22,%22%22);eval(code)%7Delse%7Bcode=code.replace(/%5Es+%7Cs+$/g,%22%22);if(code.length%3E0)%7Bwindow.open(code)%7D%7D%7D%7D)(%5B%7Btitle:%22%E7%A0%B4%E9%99%A4%E5%8F%B3%E9%94%AE%E8%8F%9C%E5%8D%95%E9%99%90%E5%88%B6%22,url:%22javascript:function%20applyWin(a)%7Bif(typeof%20a.__nnANTImm__===%5Cx22undefined%5Cx22)%7Ba.__nnANTImm__=%7B%7D;a.__nnANTImm__.evts=%5B%5Cx22mousedown%5Cx22,%5Cx22mousemove%5Cx22,%5Cx22copy%5Cx22,%5Cx22contextmenu%5Cx22%5D;a.__nnANTImm__.initANTI=function()%7Ba.__nnantiflag__=true;a.__nnANTImm__.evts.forEach(function(c,b,d)%7Ba.addEventListener(c,this.fnANTI,true)%7D,a.__nnANTImm__)%7D;a.__nnANTImm__.clearANTI=function()%7Bdelete%20a.__nnantiflag__;a.__nnANTImm__.evts.forEach(function(c,b,d)%7Ba.removeEventListener(c,this.fnANTI,true)%7D,a.__nnANTImm__);delete%20a.__nnANTImm__%7D;a.__nnANTImm__.fnANTI=function(b)%7Bb.stopPropagation();return%20true%7D;a.addEventListener(%5Cx22unload%5Cx22,function(b)%7Ba.removeEventListener(%5Cx22unload%5Cx22,arguments.callee,false);if(a.__nnantiflag__===true)%7Ba.__nnANTImm__.clearANTI()%7D%7D,false)%7Da.__nnantiflag__===true?a.__nnANTImm__.clearANTI():a.__nnANTImm__.initANTI()%7DapplyWin(top);var%20fs=top.document.querySelectorAll(%5Cx22frame,%20iframe%5Cx22);for(var%20i=0,len=fs.length;i%3Clen;i++)%7Bvar%20win=fs%5Bi%5D.contentWindow;try%7Bwin.document%7Dcatch(ex)%7Bcontinue%7DapplyWin(fs%5Bi%5D.contentWindow)%7D;void%200;%22%7D,%7Btitle:%22%E7%A0%B4%E9%99%A4%E9%80%89%E6%8B%A9%E5%A4%8D%E5%88%B6%E9%99%90%E5%88%B6%22,url:%22javascript:(function()%7Bvar%20doc=document;var%20bd=doc.body;bd.onselectstart=bd.oncopy=bd.onpaste=bd.onkeydown=bd.oncontextmenu=bd.onmousemove=bd.onselectstart=bd.ondragstart=doc.onselectstart=doc.oncopy=doc.onpaste=doc.onkeydown=doc.oncontextmenu=null;doc.onselectstart=doc.oncontextmenu=doc.onmousedown=doc.onkeydown=function%20()%7Breturn%20true;%7D;with(document.wrappedJSObject%7C%7Cdocument)%7Bonmouseup=null;onmousedown=null;oncontextmenu=null;%7Dvar%20arAllElements=document.getElementsByTagName(%5Cx27*%5Cx27);for(var%20i=arAllElements.length-1;i%3E=0;i--)%7Bvar%20elmOne=arAllElements;with(elmOne.wrappedJSObject%7C%7CelmOne)%7Bonmouseup=null;onmousedown=null;%7D%7Dvar%20head=document.getElementsByTagName(%5Cx27head%5Cx27)%5B0%5D;if(head)%7Bvar%20style=document.createElement(%5Cx27style%5Cx27);style.type=%5Cx27text/css%5Cx27;style.innerHTML=%5Cx22html,*%7B-moz-user-select:auto!important;%7D%5Cx22;head.appendChild(style);%7Dvoid(0);%7D)();%22%7D%5D)");
                }
                },
{
       label: "切换文字编码",
       oncommand: '((function () { var charset = gBrowser.mCurrentBrowser._docShell.charset; BrowserSetForcedCharacterSet(charset == "UTF-8" ? "GBK" : "UTF-8");    })).call(this, event);',
       image:""},
{
		label:"页面自动滚屏",
		url:"javascript:var%20_ss_interval_pointer;_ss_speed=3;_ss_speed_pairs=[[0,0],[1,200.0],[1,120.0],[1,72.0],[1,43.2],[1,25.9],[2,31.0],[4,37.2],[8,44.8],[8,26.4],[16,32.0]];_ss_last_onkeypress=document.onkeypress;_ss_stop=function(){clearTimeout(_ss_interval_pointer)};_ss_start=function(){_ss_abs_speed=Math.abs(_ss_speed);_ss_direction=_ss_speed/_ss_abs_speed;_ss_speed_pair=_ss_speed_pairs[_ss_abs_speed];_ss_interval_pointer=setInterval('scrollBy(0,'+_ss_direction*_ss_speed_pair[0]+');%20if((pageYOffset<=1)||(pageYOffset==document.height-innerHeight))%20_ss_speed=0;',_ss_speed_pair[1]);};_ss_adj=function(q){_ss_speed+=q;if(Math.abs(_ss_speed)>=_ss_speed_pairs.length)_ss_speed=(_ss_speed_pairs.length-1)*(_ss_speed/Math.abs(_ss_speed))};_ss_quit=function(){_ss_stop();document.onkeypress=_ss_last_onkeypress;};document.onkeypress=function(e){if((e.charCode==113)||(e.keyCode==27)){_ss_quit();return;};if(e.charCode>=48&&e.charCode<=57)_ss_speed=e.charCode-48;else%20switch(e.charCode){case%2095:_ss_adj(-2);case%2045:_ss_adj(-1);break;case%2043:_ss_adj(2);case%2061:_ss_adj(1);break;};_ss_stop();_ss_start();};_ss_stop();_ss_start();",
		image:" "
	},{
		label:"页面自动刷新",
		url:"javascript:(function(p){open('','',p).document.write('%3Cbody%20id=1%3E%3Cnobr%20id=2%3E%3C/nobr%3E%3Chr%3E%3Cnobr%20id=3%3E%3C/nobr%3E%3Chr%3E%3Ca%20href=%22#%22onclick=%22return!(c=t)%22%3EForce%3C/a%3E%3Cscript%3Efunction%20i(n){return%20d.getElementById(n)}function%20z(){c+=0.2;if(c%3E=t){c=0;e.location=u;r++}x()}function%20x(){s=t-Math.floor(c);m=Math.floor(s/60);s-=m*60;i(1).style.backgroundColor=(r==0||c/t%3E2/3?%22fcc%22:c/t%3C1/3?%22cfc%22:%22ffc%22);i(2).innerHTML=%22Reloads:%20%22+r;i(3).innerHTML=%22Time:%20%22+m+%22:%22+(s%3C10?%220%22+s:s)}c=r=0;d=document;e=opener.top;u=prompt(%22URL%22,e.location.href);t=u?prompt(%22Seconds%22,60):0;setInterval(%22z()%22,200);if(!t){window.close()}%3C/script%3E%3C/body%3E')})('status=0,scrollbars=0,width=100,height=115,left=1,top=1')",
		image:" "
	},
{
		label:"垂直分屏浏览",
		keyword: 'czfp',
		image:" "
	},{
		label:"水平分屏浏览",
		keyword: 'spfp',
		image:" "
	},
		{
       label: "恢复默认窗口",
       tooltiptext: "需要根据自己屏幕的大小手动调整数值",
       oncommand: function(e) {window.innerWidth=1240, window.innerHeight=740; window.moveTo(100, 50);},//可视区域居中
       image:""},
];

		var menu = PageMenu({
		label: "阅读辅助工具",
		condition: 'normal',
		insertBefore: 'context-openlinkincurrent',
		image:""
	});
	menu(items);
};




//复制链接文本地址
new function () {
	var items = [
		{
		label:"复制链接文本",
		text:"%LINK_TEXT%",
		image:" "
	},
{
		label:"复制链接地址",
     tooltiptext: "左键:复制链接地址\n右键:复制链接decode地址",
		onclick: function(e) {
switch(e.button) {
case 0:
Components.classes['@mozilla.org/widget/clipboardhelper;1'].getService(Components.interfaces.nsIClipboardHelper).copyString(gContextMenu.linkURL);;
break;
case 2:
Components.classes['@mozilla.org/widget/clipboardhelper;1'].getService(Components.interfaces.nsIClipboardHelper).copyString(decodeURIComponent(gContextMenu.linkURL));;
break;
}
},
		image:" "
	},
{
		label:"复制链接文本+地址",
		text:"%LINK_TEXT%\n%l",
		image:""
	},
{
    label: "复制链接源代码",
    tooltiptext: "左键:HTML代码\n中键:MD代码\n右键:UBB代码",
    onclick: function(event) {
        var formats = [
           '<a href="%l" target="_blank">%LINK_TEXT%</a>',
            "[url=%RLINK_OR_URL%]%RLT_OR_UT%[/url]",
            "[%RLT_OR_UT%](%RLINK_OR_URL%)",
        ];
        var str = addMenu.convertText(formats[event.button]);
        addMenu.copy(str);
        if (event.button === 1) { // 中键点击后自动关闭菜单
            document.getElementById("contentAreaContextMenu").hidePopup();
        }
    },
    image: ""
},
{
    label: "复制链接短网址",
    image: "",
    oncommand: function() {
        var url = addMenu.convertText("%RLINK_OR_URL%");
        var form = new FormData();
        form.append('url', url);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://dwz.cn/create.php", true);
        xhr.onload = function() {
            var obj = JSON.parse(xhr.responseText);
            addMenu.copy(obj.tinyurl);
        }
        xhr.send(form);
    }
},

];
	var menu = PageMenu({ condition:'link', insertBefore:'context-openlink', onpopupshowing: syncHidden });
	menu(items);
	items.forEach(function(it){
		if (it.command)
			css('#contentAreaContextMenu[addMenu~="link"] #' + it.command + '{ display: none !important; }')
	});
};

//打开链接的各种方法
new function () {
	var items = [
	{
    label:"新标签页打开",
	  image: "", 
	  oncommand: "gContextMenu.openLinkInTab(event);",},
{
			label: '当前标签打开'
			,image:""
			,oncommand: 'document.getElementById("context-openlinkincurrent").doCommand();'
		},{
		label:"侧边栏中打开",
		oncommand:"openWebPanel(gContextMenu.linkText(), gContextMenu.linkURL);",
		image:""
	},
   {
		label:"IE浏览器打开",
		oncommand: function() {
	try {
		var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProgF", Components.interfaces.nsILocalFile);
		file.append("Internet Explorer");
		file.append("iexplore.exe");
		var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
		process.init(file);
		process.run(false, [gContextMenu.linkURL], 1);
	} catch (ex) {
		alert("打开IE失败!")
	}
},
		image:""
	},
{
		label:"指定程序打开",
		text:"%l",
    tooltiptext: "需要手动指定其他浏览器.exe所在位置",
		exec:"D:\\Chrome\\ChromePortable.exe",
		image:""
	},
	{
		label:"隐私窗口打开",
		oncommand:"gContextMenu.openLinkInPrivateWindow();",
	image:""
	},
	{
		label:"谷歌缓存打开",
    oncommand: "gBrowser.addTab('https://webcache.googleusercontent.com/search?q=cache:'+ decodeURIComponent(gContextMenu.linkURL));",
		image:" "
	},	
{
		label:"谷歌文档打开",
    oncommand: "gBrowser.addTab('https://docs.google.com/viewer?url='+ decodeURIComponent(gContextMenu.linkURL));",
		image:" "
	},

];
	var menu = PageMenu({ condition: 'link', insertBefore:'context-openlink', onpopupshowing: syncHidden});
	menu(items);
	items.forEach(function(it){
		if (it.command)
			css('#contentAreaContextMenu[addMenu~="link"] #' + it.command + '{ display: none !important; }')
	});
};

//复制文本
new function () {
	var items = [
	{ command: 'context-copy',
	  image:"" },
	{
		label:"复制纯文本",
		text:"%SEL%",
		image:""
	},
{
		label:"复制源代码",
		image:"",
	oncommand: function () {
			var div = content.document.createElement('div');
			div.appendChild(content.getSelection().getRangeAt(0).cloneContents());
			Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper).copyString(div.innerHTML);
		}},
{
    label: "保存选定文本",
    condition: "select",
    image:"",
    oncommand: function() {
        if (!window.NetUtil) Cu.import("resource://gre/modules/NetUtil.jsm");
        if (!window.FileUtils) Cu.import("resource://gre/modules/FileUtils.jsm");

        goDoCommand('cmd_copy');
        var data = readFromClipboard();

        var fp = Cc["@mozilla.org/filepicker;1"].createInstance(Ci.nsIFilePicker);
        fp.init(window, "另存为", Ci.nsIFilePicker.modeSave);
        fp.appendFilter("文本文件", "*.txt");
        fp.defaultString = content.document.title + '.txt';

        var res = fp.show();
        if (res != Ci.nsIFilePicker.returnCancel) {
            var aFile = fp.file;

            var ostream = FileUtils.openSafeFileOutputStream(aFile);

            var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].createInstance(Ci.nsIScriptableUnicodeConverter);
            converter.charset = "gbk";
            var istream = converter.convertToInputStream(data);

            NetUtil.asyncCopy(istream, ostream, function(status) {
                if (!Components.isSuccessCode(status)) {
                    // Handle error!
                    return;
                }

                aFile.launch();
            });
        }
    }}
];
	
	var menu = PageMenu({ condition:'select', insertBefore:'context-paste', onpopupshowing: syncHidden,image:""  });
	menu(items);
	//page({ condition:'select', insertBefore:'context-sep-copylink' });
	items.forEach(function(it){
		if (it.command)
			css('#contentAreaContextMenu[addMenu~="select"] #' + it.command + '{ display: none !important; }')
	});
};


//翻译文本
page([
	{
		label:"翻译选中文本",
		condition: "select",
		image:"",
	insertAfter: "context-inspect",
	oncommand: "gBrowser.selectedBrowser.messageManager.sendAsyncMessage('FGgTranslator', readFromClipboard());",
}
]);




/*右键加图标*/
//链接另存为
page(
  { id: 'context-savelink',clone :false,image: "" 
});
//图像复制
page(
{ id: 'context-copyimage-contents',clone :false,image:
""
});
//图像另存为
page(
{ id: 'context-saveimage',clone :false,image:
""
});
page(
{ id: 'context-bookmarklink',clone :false,image:
""
});
//复制
page(
{ id: 'context-copy',clone :false,image:
""
});
//撤销
page(
{ id: 'context-undo',clone :false,image:
""
});
//剪切
page(
{ id: 'context-cut',clone :false,image:
""
});
//粘贴
page(
{ id: 'context-paste',clone :false,image:
""
});  
//删除
page(
{ id: 'context-delete',clone :false,image:
""
});     
//此框架
page(
{ id: 'frame',clone :false,image:
""
});
//打开链接
page(
{ id: 'context-openlinkincurrent',clone :false,image:
""
});
//分享此页面     
page(
  { id: 'context-sharepage',insertAfter:"context-inspect",clone :false,image: "" 
});
//播放速度     
page(
  { id: 'context-media-playbackrate',clone :false,image: "" 
});
//addmenuplus
page(
{id: 'addMenu-rebuild',clone :false,image: ""});
//开发者工具栏
page(
{id: 'webDeveloperMenu',clone :false,image: ""});
//查看图像信息
page(
{id: 'context-viewimageinfo',clone :false,image: ""});





//当前页面
new function () {
	var items = [
{
label:"移动到侧边栏",
id:"context_TabFloatSidebar",
oncommand:"openWebPanel(content.document.title, content.location);",
image:""
},{
label:"小窗模式打开",
id:"context_openTabInChrome",
image:"",
oncommand: function() {window.open(decodeURIComponent(gBrowser.currentURI.spec), "_blank","resizable,scrollbars,status,title").resizeTo(430, 670); gBrowser.removeCurrentTab();},
},{
label:"移动到新窗口",
id:"context_openTabInWindow2",
image:"",
oncommand:"gBrowser.replaceTabWithWindow(decodeURIComponent(gBrowser.currentURI.spec))",
},{
		label:"IE浏览器打开",
		oncommand: function() {
	try {
		var file = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties).get("ProgF", Components.interfaces.nsILocalFile);
		file.append("Internet Explorer");
		file.append("iexplore.exe");
		var process = Cc["@mozilla.org/process/util;1"].createInstance(Ci.nsIProcess);
		process.init(file);
		process.run(false, [gBrowser.currentURI.spec], 1);
	} catch (ex) {
		alert("打开IE失败!")
	}
},
		image:""},{
		label:"指定程序打开",
		text:"%u",
    tooltiptext: "需要手动指定其他浏览器.exe所在位置",
		exec:"D:\\Chrome\\ChromePortable.exe",
		image:""
	},{
		label:"隐私窗口打开",
		oncommand:"openLinkIn(content.location, 'window',{private:true});",
	image:""
	},


];
	
var menu = PageMenu({condition: 'normal', insertBefore: 'context-openlinkincurrent',image:"", onpopupshowing: syncHidden });
	menu(items);
};





//当前页面
new function () {
	var items = [
{
				label : '翻译当前页面',
image:"",
				oncommand :
			function() {
               gBrowser.loadURI("javascript:%20void((function()%20{var%20element%20=%20document.createElement('script');element.id%20=%20'outfox_seed_js';element.charset%20=%20'utf-8',element.setAttribute('src',%20'http://fanyi.youdao.com/web2/seed.js?'%20+%20Date.parse(new%20Date()));document.body.appendChild(element);})())");

				},
			}, 
{
				label : '谷歌页内翻译',
				image : "",
				oncommand :
				function ()
				{
					gBrowser.loadURI("javascript:{d=document;b=d.body;o=d.createElement('scri'+'pt');o.setAttribute('src','https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit');o.setAttribute('type','text/javascript');b.appendChild(o);v=b.insertBefore(d.createElement('div'),b.firstChild);v.id='google_translate_element';v.style.display='none';p=d.createElement('scri'+'pt');p.text='function%20googleTranslateElementInit(){new%20google.translate.TranslateElement({pageLanguage:%22%22},%22google_translate_element%22);}';p.setAttribute('type','text/javascript');b.appendChild(p);}void%200")
				},
			},
{},
{
    label: "谷歌弹窗翻译",
    url: "javascript:(function(){var%20t=((window.getSelection&&window.getSelection())||(document.getSelection&&document.getSelection())||(document.selection&&document.selection.createRange&&document.selection.createRange().text));var%20e=(document.charset||document.characterSet);if(t!=''){window.open('https://translate.google.com/translate_t?hl=zh-CN#auto|zh-CN|'+t);}else{window.open('https://translate.google.com/translate?u='+escape(location.href)+'&hl=zh-CN&ie='+e+'&sl=auto&tl=zh-CN');};})();",
    image: ""
},{
    label: "必应弹窗翻译",
    oncommand: function() {gBrowser.addTab('www.microsofttranslator.com/bv.aspx?from=&to=zh-CHS&a=' + decodeURIComponent(gBrowser.currentURI.spec));},
    image: ""
},
{
    label: "百度弹窗翻译",
    url: "javascript:(function(){window.open('http://fanyi.baidu.com/transpage?query='+escape(document.location.href)+'&from=auto&to=zh&source=url&render=1')})();",
    image: ""
},
{
    label: "沪江划词翻译",
    url: "javascript:void((function(){hjelm=document.createElement('script');hjelm.setAttribute('src','http://dict.hjenglish.com/app/js/dict_ajax.js');document.body.appendChild(hjelm);})())",
    image: ""
},
{},
{
		label:"繁体转为简体",
		url:"javascript:(function(){var%20s=document.getElementById(%22tongwenlet_cn%22);if(s!=null){document.body.removeChild(s);}var%20s=document.createElement(%22script%22);s.language=%22javascript%22;s.type=%22text/javascript%22;s.src=%22https://git.oschina.net/runningcheese/JiathisQR.js/raw/master/bookmarklet_cn.js%22;s.id=%22tongwenlet_cn%22;document.body.appendChild(s);%20})();",
		image:" "
	},{
		label:"简体转为繁体",
		url:"javascript:(function(){var%20s=document.getElementById(%22tongwenlet_cn%22);if(s!=null){document.body.removeChild(s);}var%20s=document.createElement(%22script%22);s.language=%22javascript%22;s.type=%22text/javascript%22;s.src=%22https://git.oschina.net/runningcheese/JiathisQR.js/raw/master/bookmarklet_tw.js%22;s.id=%22tongwenlet_cn%22;document.body.appendChild(s);%20})();",
		image:" "
	},

];
	
var menu = PageMenu({condition: 'normal', insertBefore: 'context-openlinkincurrent',image:"", onpopupshowing: syncHidden });
	menu(items);
};




//当前页面
page({
    id:"openimagesfolder",
    label: "打开图像位置",
    tooltiptext: "左键：桌面\n中键：D盘\n右键：下载",
    onclick: function(e) {
        var uri = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(gContextMenu.imageURL, null, null)
        switch(e.button) {
            case 0:
            var file  = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); var process = Components.classes['@mozilla.org/process/util;1'] .createInstance(Components.interfaces.nsIProcess); var path = "C:\\Users\\Administrator\\Desktop"; file.initWithPath(path); file.launch();  return file; 
            break;
            case 1:
            var file  = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); var process = Components.classes['@mozilla.org/process/util;1'] .createInstance(Components.interfaces.nsIProcess); var path = "D:\\"; file.initWithPath(path); file.launch();  return file; 
            break;
            case 2:
             var file  = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); var process = Components.classes['@mozilla.org/process/util;1'] .createInstance(Components.interfaces.nsIProcess); var path = "C:\\Users\\Administrator\\Downloads\\"; file.initWithPath(path); file.launch();  return file; 
            break;
        }
    },
   condition: "image",
   insertAfter: "context-saveimage",
   image:"",
});

//为“打开图像位置”增加一个分割条
page({
   condition: "image",
   insertBefore: "openimagesfolder",
});

//当前页面
page({
    label: "将图像另存到桌面",
    tooltiptext: "左键：桌面\n中键：D盘\n右键：下载",
    onclick: function(e) {
        var uri = Components.classes["@mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService).newURI(gContextMenu.imageURL, null, null)
        switch(e.button) {
            case 0:
                var path = "C:\\Users\\Administrator\\Desktop\\";
            break;
            case 1:
                var path = "D:\\";
            break;
            case 2:
                var path = "C:\\Users\\Administrator\\Downloads\\";
            break;
        }
        var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
        file.initWithPath(path);
        file.append(getDefaultFileName(null, uri));
        internalSave(null, null, null, null, null, null, null, {
            file: file,
            uri: uri
        }, null, internalSave.length === 12 ? document : true, internalSave.length === 12 ? true : null, null);
    },
   condition: "image",
   insertAfter: "context-saveimage",
   image:"",
});




//当前页面
new function () {
	var items = [
{
    label: "分享当前页面",
    tooltiptext: "第一次点击速度稍慢",
    url: "javascript:void((function(svc)%20{var%20d=document,w=window,p=0,b=function(){if(!p){p=1;if(_atc.xol)_adr.onReady();if(w.addthis_sendto)addthis_sendto(svc||'bkmore',{product:'bmt-'+_atc.ver})}else{p=0;if(_atw)_atw.clb()}};if(!w._atc){var%20ol=w.addthis_onload||[],o=d.createElement('script');w.addthis_product%20=%20'bmt-250';o.src='https://git.oschina.net/runningcheese/JiathisQR.js/raw/master/addthis_widget.js#domready=1&username=bookmarklet';ol.push(b);w.addthis_onload=ol;d.getElementsByTagName('body')[0].appendChild(o)}else%20b()})())",
    image: ""
},
{
    label: "分享当前页面2",
    url: "javascript:(function(){var%20w=window,d=document,s;if(!w.jiathis){w.jiathis=1;s=d.createElement('script');s.src='http://www.jiathis.com/code/j.js';d.getElementsByTagName('head')[0].appendChild(s);s=null}else{$CKE.center()}})()",
    image: ""
},{ 
    label: "邮件发送当前页",
    id: 'context-sendlink',clone :false,
    command:'Browser:SendLink',
    condition: "normal",
    image: "",
},{
    label: "发送到百度云",
    url: "javascript:void%20(function(d)%20{var%20e%20=%20d.createElement('script');e.byebj=true;e.src%20=%20'http://s.wenzhang.baidu.com/js/pjt/content_ex/page/bookmark.js?s=bm&t='%20+%20(+new%20Date());var%20b%20=%20d.getElementsByTagName('body')[0];b.firstChild%20?%20b.insertBefore(e,%20b.firstChild)%20:%20b.appendChild(e);}(document));",
    image: ""
},{
    label: "发送到有道云",
    url: "javascript:(function(){CLIP_HOST='http://note.youdao.com/yws';try{var%20x=document.createElement('SCRIPT');x.type='text/javascript';x.src=CLIP_HOST+'/YNoteClipper.js?'+(new%20Date().getTime()/100000);x.charset='utf-8';document.getElementsByTagName('head')[0].appendChild(x);}catch(e){alert(e);}})();",
    image: ""
},{
    label: "发送到为知笔记",
    tooltiptext: "需要修改成你的为知笔记ID",
       url: "javascript:window.open('http://note.wiz.cn/url2wiz?url=' + encodeURIComponent(document.location.href)+'&folder=%2FMy%20Notes%2F&user=为知笔记ID&content-only=false&bookmark=1');",
    image: ""
},
{
    label: "发送到Evernote",
    url: "javascript:(function(){EN_CLIP_HOST='http://www.evernote.com';try{var%20x=document.createElement('SCRIPT');x.type='text/javascript';x.src=EN_CLIP_HOST+'/public/bookmarkClipper.js?'+(new%20Date().getTime()/100000);document.getElementsByTagName('head')[0].appendChild(x);}catch(e){location.href=EN_CLIP_HOST+'/clip.action?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title);}})();",
    image: ""
},
{
    label: "发送到Onenote",
    url: "javascript:(function(){var%20jsCode=document.createElement('script');jsCode.setAttribute('src','https://www.onenote.com/Clipper/Root?ClipperId=ON-95a88c52-50d6-4c35-b134-2bdd4f682242&ClipperType=Bookmarklet&ClipperVersion=2.0.2');jsCode.setAttribute('id','oneNoteCaptureRootScript');jsCode.setAttribute('type','text/javascript');document.body.appendChild(jsCode);})()",
    image: ""
},
{
		label:"发送到本地Onenote",
    tooltiptext: "需要手动指定OneNote.exe所在位置",
		image:"",
		oncommand: function(){
			var onenotePath = "C:\\Program Files\\Microsoft Office\\Office15\\Onenote.exe";
			var focusedWindow = document.commandDispatcher.focusedWindow;
			var selection = new String(focusedWindow.getSelection());
			if (selection.length == 0) {
				 goDoCommand('cmd_selectAll');
				 var allSelection = new String(focusedWindow.getSelection());
				 if (allSelection.length == 0)return;
				 goDoCommand('cmd_copy');
				 goDoCommand('cmd_selectNone');
			}
			else
			{
				 goDoCommand('cmd_copy');
			}
			var file = Components.classes["@mozilla.org/file/local;1"].createInstance(Components.interfaces.nsILocalFile);
			file.initWithPath(onenotePath);
			var process = Components.classes["@mozilla.org/process/util;1"].createInstance(Components.interfaces.nsIProcess);
			process.init(file);
			var args = ["/sidenote", "/paste"];
			process.run(false, args, args.length);
		}
},

];
	
var menu = PageMenu({condition: 'normal', insertBefore: 'context-openlinkincurrent',image:"", onpopupshowing: syncHidden });
	menu(items);
};


//图片
new function () {
	var items = [
	{command: 'context-copyimage-contents',
	 image:""
	},
 {
    label:"复制图像地址",
	  image: "",
	  class: "context-copyimage", 
	  oncommand: "gContextMenu.copyMediaLocation();",
},{
    label: "复制 GIF 图片",
    image: "",
    onclick: function(event) {
        if (event.button === 0) {
            var selection = content.getSelection();
            var ranges = [];
            for (var i = 0; i < selection.rangeCount; i++) ranges.push(selection.getRangeAt(i));
            var range = document.createRange();
            range.selectNode(document.popupNode);
            selection.removeAllRanges();
            selection.addRange(range);
            goDoCommand("cmd_copy");
            selection.removeAllRanges();
            for (i in ranges) selection.addRange(ranges);
        }
    }
},
	   {
		label: '谷歌以图搜图',
		image:"",
   oncommand: function() {
        var url = encodeURIComponent(gContextMenu.mediaURL || gContextMenu.imageURL || gContextMenu.bgImageURL);
        gBrowser.addTab('https://www.google.com/searchbyimage?safe=off&image_url=' + url);
    }
	},
{
    label: "OCR文字识别",
    image:"",
    oncommand: function() {
        //apikey
        var apikey = "aee93efca6438819212e64aa47711ee0";
   
        var base64str = img2base64(gContextMenu.mediaURL || gContextMenu.imageURL || gContextMenu.bgImageURL).replace("data:image/jpeg;base64,", "");
        var xmlHttp = new XMLHttpRequest();
        xmlHttp.open("POST", "http://apis.baidu.com/apistore/idlocr/ocr", true);
        xmlHttp.setRequestHeader("apikey", apikey);
        var formData = new FormData();
        for(var d of ("fromdevice=pc&clientip=10.10.10.0&detecttype=LocateRecognize&languagetype=CHN_ENG&imagetype=1&image=" + base64str).split('&'))
            formData.append.apply(formData, d.split('=', 2));
        xmlHttp.send(formData);
        xmlHttp.onload = function() {
            if (xmlHttp.status == 200) {
                var data = JSON.parse(xmlHttp.responseText);
                if (data.errNum != 0)
                    alert("错误：" + data.errMsg);
                else {
                    var str = "";
                    for (var i in data.retData) str += data.retData[i].word;
                    alert("识别内容：" + str);//弹窗提示
                    addMenu.copy(str);//自动复制识别内容到剪贴板
                }
            }
        };
   
        function img2base64(imgsrc) {
            if (typeof imgsrc == 'undefined') return "";
   
            const NSURI = "http://www.w3.org/1999/xhtml";
            var img = new Image();
            var that = this;
            var canvas,
                isCompleted = false;
            img.onload = function() {
                var width = this.naturalWidth,
                    height = this.naturalHeight;
                canvas = document.createElementNS(NSURI, "canvas");
                canvas.width = width;
                canvas.height = height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(this, 0, 0);
                isCompleted = true;
            };
            img.onerror = function() {
                Components.utils.reportError("Count not load: " + imgsrc);
                isCompleted = true;
            };
            img.src = imgsrc;
   
            var thread = Cc['@mozilla.org/thread-manager;1'].getService().mainThread;
            while (!isCompleted) {
                thread.processNextEvent(true);
            }
   
            var data = canvas ? canvas.toDataURL("image/jpeg", 1) : "";
            canvas = null;
            return data;
        }
    }
},
{
    label: "用PS打开图片",
   tooltiptext: "需要手动指定Photoshop.exe所在位置",
   image: "",
    oncommand: function() {
        var imageUrl = (gContextMenu.mediaURL || gContextMenu.imageURL);
        if (imageUrl.match(/(\.jpe?g|\.png|\.gif|\.jpg)/i)) var extension = RegExp.$1;
    else var extension = ".jpg";
 
        var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsILocalFile);
        file.append(new Date().getTime() + extension);
 
        Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Ci.nsIWebBrowserPersist)
            .saveURI(Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
                .newURI(imageUrl, null, null), null, null, null, null, null, file, null);
            var ps="D:\\Adobe CC 2014\\Adobe Photoshop\\Adobe Photoshop CC 2014 (32 Bit)\\Photoshop.exe";
        setTimeout(function() {
            addMenu.exec(ps,("%1 "+file.path));
        }, 100);
    },
},{
    label: "在线编辑图片",
    condition: "image",
    tooltiptext: "图片地址已经复制到粘贴板",
    image: "",
    oncommand: "gContextMenu.copyMediaLocation(); gBrowser.selectedTab = gBrowser.addTab('https://pixlr.com/editor/');",
},
{
label: "打开图像RAR",
condition: "image",
image:"",
oncommand: function() {
var imageUrl = (gContextMenu.mediaURL || gContextMenu.imageURL);
imageUrl = imageUrl.replace(/\.jpg\.thumb\.jpg$/, '.jpg');
var file = Cc["@mozilla.org/file/directory_service;1"].getService(Ci.nsIProperties).get("TmpD", Ci.nsILocalFile);
file.append(new Date().getTime() + ".rar");
Cc["@mozilla.org/embedding/browser/nsWebBrowserPersist;1"].createInstance(Ci.nsIWebBrowserPersist)
.saveURI(Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService)
.newURI(imageUrl, null, null), null, null, null, null, null, file, null);
setTimeout(function() {
file.launch();
}, 500);
},
},
{
		label: 'QR二维码解析',
		image:"",
   oncommand: function() {
        function getDataURLFromIMG(imgsrc) {
            if (typeof imgsrc == 'undefined') return "";
            const NSURI = "http://www.w3.org/1999/xhtml";
            var img = new Image();
            var that = this;
            var canvas,
                isCompleted = false;
            img.onload = function() {
                var width = this.naturalWidth,
                    height = this.naturalHeight;
                canvas = document.createElementNS(NSURI, "canvas");
                canvas.width = width;
                canvas.height = height;
                var ctx = canvas.getContext("2d");
                ctx.drawImage(this, 0, 0);
                isCompleted = true;
            };
            img.onerror = function() {
                Components.utils.reportError("Count not load: " + imgsrc);
                isCompleted = true;
            };
            img.src = imgsrc;
 
            var thread = Cc['@mozilla.org/thread-manager;1'].getService().mainThread;
            while (!isCompleted) {
                thread.processNextEvent(true);
            }
            var data = canvas ? canvas.toDataURL("image/gif", 1) : "";
            canvas = null;
            return data;
        };
        function getBlobFromDataURL(dataurl) {
            var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
            while(n--){
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], {type:mime});
        }
        function Deal(ffile){
            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open("POST", "http://qring.org/decode", true);
            var formdata = new FormData();
            formdata.append("file", ffile);
            xmlHttp.send(formdata);
            xmlHttp.onload = function() {
                if (xmlHttp.status == 200) {
                    var data = JSON.parse(xmlHttp.responseText);
                    if (data.msg != "SUCCESS")
                        alert("错误：" + data.msg);
                    else {
                        var text=data.data.text;
                        if(text.indexOf("http") == 0){
                            addMenu.copy(text);
                            var message = confirm("识别内容:[ "+text+" ]~\n检查到为【链接】是否打开？")
                            if(message == true){
                                gBrowser.addTab(text);
                            }else{
                            }
                        }else{
                            addMenu.copy(text);
                            alert("识别内容:[ "+text+" ]\n结果已经复制到剪切板了~");
                        }
                    }
                }else if(xmlHttp.status == 500){
                    alert("错误：解析失败");
                }
            };
        }
        Deal(getBlobFromDataURL(getDataURLFromIMG(gContextMenu.mediaURL || gContextMenu.imageURL || gContextMenu.bgImageURL)));
    }
	},
{
		label:"复制Base64码",
		text:"%IMAGE_BASE64%",
		image:" "
	},
];
	
	var menu = PageMenu({ condition:'image', id:'context-copyimage_new',insertAfter:'context-viewimage', icon:'image', onpopupshowing: syncHidden});
	menu(items);
	items.forEach(function(it){
		if (it.command)
			css('#contentAreaContextMenu[addMenu~="image"] #' + it.command + '{ display: none !important; }')
	});
};

page(
{
    label: "文字语言转换",
    tooltiptext: "左键：转化为英文\n中键：转化为中文简体\n右键：转化为中文繁体",
    image:"",
    onclick: function(event) {
        var urls = [
            "auto&tl=en&dt=t&q=",
            "auto&tl=zh-CN&dt=t&q=",
            "auto&tl=zh-TW&dt=t&q="
        ];
        var focused = document.commandDispatcher.focusedElement,
            select = getBrowserSelection();
        if (!select) {var txt = focused.value}
        else {var txt = getBrowserSelection();}
        var xmlhttp = new XMLHttpRequest;
        xmlhttp.open("get", "https://translate.google.com/translate_a/single?client=gtx&sl=" + urls[event.button] + txt, 0);
        xmlhttp.send();
        for(var i = 0; i < xmlhttp.responseText.length; i++) {
            var output = eval("(" + xmlhttp.responseText + ")")[0][i][0];
            if (focused && !select) {
                focused.value = output;
            }
            else if (focused && select) {
                goDoCommand("cmd_delete");
                var aStart = aEnd = focused.selectionStart;
                focused.value = focused.value.slice(0, aStart) + output + focused.value.slice(aEnd);
                var aOffset = aStart + output.length;
                focused.setSelectionRange(aOffset, aOffset);
            } else if (!focused) {
                Components.classes['@mozilla.org/widget/clipboardhelper;1'].createInstance(Components.interfaces.nsIClipboardHelper).copyString(output);
                goDoCommand("cmd_paste");
            }
        };
    },
    condition:'input'
});

//快捷回复
new function(){
	var items = [
		{label:"用户名Username", input_text: "你的用户名",image:" "},
		{label:"邮箱E-mail", input_text: "你的邮箱@qqcom",image:" "},
		{label:"网站Website", input_text: "http://www.yoursite.com",image:" "},
    {},
		{label:"不明觉厉~~~", input_text: "虽然不知道LZ在说什么但是感觉很厉害的样子～",image:" "},
		{label:"不用客气~~~", input_text: "不用客气，大家互相帮助……\n\u256E\uFF08\u256F\u25C7\u2570\uFF09\u256D",image:" "},
		{label:"反馈情况再说", input_text: "Mark，看反馈情况再说。。。",image:" "},
		{label:"看起来很不错", input_text: "看起来很不错哦，收藏之~~~\n谢谢LZ啦！！！",image:" "},
		{label:"谢谢楼主分享", input_text: "谢谢楼主的分享!这个绝对要顶！！！",image:" "},
		{label:"楼上正解~~~", input_text: "楼上正解……\u0285\uFF08\u00B4\u25D4\u0C6A\u25D4\uFF09\u0283",image:" "},
		{label:"坐等楼下解答", input_text: "坐等楼下高手解答~~~⊙_⊙",image:" "},
		{label:"这个要支持~~~", input_text: "很好、很强大，这个一定得支持！！！",image:" "},
		{label:"不明真相的~~~", input_text: "不明真相的围观群众~~~\u0285\uFF08\u00B4\u25D4\u0C6A\u25D4\uFF09\u0283",image:" "},
		{label:"没图没真相~~~", input_text: "没图没真相，纯支持下了~~~",image:" "},
		{label:"嘿嘿~~~", input_text: "\u2606\u002E\u3002\u002E\u003A\u002A\u0028\u563F\u00B4\u0414\uFF40\u563F\u0029\u002E\u3002\u002E\u003A\u002A\u2606",image:" "}
	];
	var menu = PageMenu({
		label:"快速输入...",
		condition:"input",
    insertBefore:"context-searchselect",
		position: 1,
		image:"",
		oncommand: function(event){
			var input_text = event.target.getAttribute('input_text');
			if(input_text) {
				addMenu.copy(input_text);
				goDoCommand("cmd_paste");
			}
		}
	});
	menu(items);
};




//颜文字输入
var Specialcharacters = PageMenu({
                label:"颜文字输入",
			         	condition:"input",
                insertBefore:"context-searchselect",
                oncommand: function(event){
                        var input_text = event.target.getAttribute('input_text');
                        if(input_text) {
                                addMenu.copy(input_text);
                                goDoCommand("cmd_paste");
                }
        },
    image:""
});

Specialcharacters([
	{id: "spe-charaters", style: "display:none;"}
]);


var SPE4 = PageMenu({
	label: "卖萌",
	condition: "input",
	insertBefore: "spe-charaters",
});
SPE4([
                {label: "｡◕‿◕｡", input_text:"｡◕‿◕｡"},
                {label: "(●'‿'●) ", input_text:"(●'‿'●) "},
                {label: "(ง •̀_•́)ง", input_text:"(ง •̀_•́)ง"},
                {label: "(๑•̀ω•́๑)", input_text:"(๑•̀ω•́๑)"}, 
                {label: "(๑¯∀¯๑)", input_text:"(๑¯∀¯๑)"},
                {label: "(๑•̀ㅂ•́)و✧", input_text:"(๑•̀ㅂ•́)و✧"},
                {label: "(๑•́ ₃ •̀๑) ", input_text:"(๑•́ ₃ •̀๑) "},
                {label: "_(:з」∠)_", input_text:"_(:з」∠)_"},
                {label: "(ฅ´ω`ฅ)", input_text:"(ฅ´ω`ฅ)"},
                {label: " (¬､¬)", input_text:" (¬､¬) "},
                {label: " ( ˙ε ˙ ) ", input_text:" ( ˙ε ˙ )"},
                {label: "(๑¯ิε ¯ิ๑) ", input_text:"(๑¯ิε ¯ิ๑) "},
                {label: "_(•̀ω•́ 」∠)_", input_text:"_(•̀ω•́ 」∠)_"},    

]);

var SPE6 = PageMenu({
	label: "不开心",
	condition: "input",
	insertBefore: "spe-charaters",
});
SPE6([
                {label: "Ծ‸Ծ", input_text:"Ծ‸Ծ"},
                {label: "●﹏●", input_text:"●﹏●"},
                {label: "≥﹏≤", input_text:"≥﹏≤"},
                {label: "◔ ‸◔？", input_text:"◔ ‸◔？"},
                {label: "ᕙ(⇀‸↼‵‵)ᕗ ", input_text:"ᕙ(⇀‸↼‵‵)ᕗ "},
                {label: "ヘ(-ω-ヘ)", input_text:"ヘ(-ω-ヘ)"},
                {label: "(￣_￣|||)", input_text:"(￣_￣|||)"},
                {label: "(눈_눈)", input_text:"(눈_눈)"},
                {label: "o(╥﹏╥)o", input_text:"o(╥﹏╥)o"},
                {label: "(￣▽￣*)b", input_text:"(￣▽￣*)b"},
                {label: "(｡•ˇ‸ˇ•｡)", input_text:"(｡•ˇ‸ˇ•｡)"},
                {label: "(｡•́︿•̀｡)", input_text:"(｡•́︿•̀｡)"},
                {label: "Σ(๑０ω０๑) ", input_text:"Σ(๑０ω０๑)"},
                 {label: "( ´◔‸◔`)", input_text:"( ´◔‸◔`)"},
                {label: "( ´･ᴗ･` )", input_text:"( ´･ᴗ･` )"},
                {label: "( ⊙⊙)!!", input_text:"( ⊙⊙)!!"}, 
                {label: "(｡ì _ í｡)", input_text:"(｡ì _ í｡)"}, 

]);

var SPE5 = PageMenu({
	label: "Emoji",
	condition: "input",
	insertBefore: "spe-charaters",
});
SPE5([
                {label: "😂", input_text:"😂"},
                {label: "😍", input_text:"😍"},
                {label: "😘", input_text:"😘"},
                {label: "😝", input_text:"😝"},
                {label: "😒", input_text:"😒"},
                {label: "😓", input_text:"😓"},
                {label: "😭", input_text:"😭"},
                {label: "😱", input_text:"😱"},
                {label: "😡", input_text:"😡"},
                {label: "😎", input_text:"😎"},
                {label: "❤️", input_text:"❤️"},
                {label: "💔", input_text:"💔"},
                {label: "👍", input_text:"👍"},
                {label: "👎", input_text:"👎"},
                {label: "👌", input_text:"👌"},
                {label: "🤝", input_text:"🤝"},

]);

var SPE7 = PageMenu({
	label: "表情包",
	condition: "input",
	insertBefore: "spe-charaters",
});
SPE7([
                {label: "Instereting", input_text:'<img src="http://ww2.sinaimg.cn/large/7a6a15d5gy1fcl9t6ejgzj2050050jr7.jpg"/>'},
                {label: "辣眼睛", input_text:'<img src="http://ww3.sinaimg.cn/large/7a6a15d5gy1fcl8r7n590j20d10cbk1y.jpg"/>'},
                {label: "爱心发射", input_text:'<img src="http://ww1.sinaimg.cn/large/7a6a15d5gy1fcl8s0pnqnj2060060aah.jpg"/>'},
                {label: "不错不错", input_text:'<img src="http://ww4.sinaimg.cn/large/7a6a15d5gy1fcl9wbtpwgg2046046jtp.gif"/>'},
                {label: "我不能接受", input_text:'<img src="http://ww4.sinaimg.cn/large/7a6a15d5gy1fcl8sipccsj208w06k0tf.jpg"/>'},
                {label: "可以，这很清真", input_text:'<img src="http://ww3.sinaimg.cn/large/7a6a15d5gy1fcl9i616lcj205i04wglr.jpg"/>'},    
                {label: "不可以，这不清真", input_text:'<img src="http://ww2.sinaimg.cn/large/7a6a15d5gy1fcl9ii6wkwj206l05wgm5.jpg"/>'},   
                {label: "厉害了，我的哥", input_text:'<img src="http://ww2.sinaimg.cn/large/7a6a15d5gy1fcl9jhl9btj20dc0a0aa7.jpg"/>'},    
                {label: "老哥，稳", input_text:'<img src="http://ww2.sinaimg.cn/large/7a6a15d5gy1fcl9jsvmwhj204e04e0sk.jpg"/>'},    
                {label: "尼克杨问题号脸", input_text:'<img src="http://ww1.sinaimg.cn/large/7a6a15d5gy1fcl6ba3jznj208k086glk.jpg"/>'},    
                {label: "在座的各位都是垃圾", input_text:'<img src="http://ww1.sinaimg.cn/large/7a6a15d5gy1fcl8ogllg0j206r03tt8o.jpg"/>'},                
                {label: "别说了....我", input_text:'<img src="http://ww4.sinaimg.cn/large/7a6a15d5gy1fcl9kl6q47g207u078av3.gif"/>'},    
                {label: "exo me?", input_text:'<img src="http://ww4.sinaimg.cn/large/7a6a15d5gy1fcl9l01y74j205k05kq2s.jpg"/>'},    
                {label: "哎呦，好叼哦", input_text:'<img src="http://ww3.sinaimg.cn/large/7a6a15d5gy1fcmq68293hj205k063js0.jpg"/>'},    
                {label: "又在背后说我帅", input_text:'<img src="http://ww1.sinaimg.cn/large/7a6a15d5gy1fcl9thd9a2j204404fglg.jpg"/>'},    
                {label: "鸡年大吉吧", input_text:'<img src="http://ww2.sinaimg.cn/large/7a6a15d5gy1fcl9vw59yaj204w050glj.jpg"/>'},  
                {label: "如此厚颜无耻之人", input_text:'<img src="http://ww2.sinaimg.cn/large/7a6a15d5gy1fcl8q2ekhkg208w06oe81.gif"/>'},  
]);

var SPE1 = PageMenu({
	label: "特殊图形",
	condition: "input",
	insertBefore: "spe-charaters",
});
SPE1([
{label: "❤♥♡",	input_text: "❤♥♡"},	
{label: "☻☺",	input_text: "☻☺"},	
{label: "♂♀",	input_text: "♂♀"},	
{label: "★☆",	input_text: "★☆"},	
{label: "■◻",	input_text: "■◻"},	
{label: "●○",	input_text: "●○"},	
{label: "▲▼",	input_text: "▲▼"},	
{label: "►◄",	input_text: "►◄"},	
{label: "√×",	input_text: "√×"},	
{label: "♪♫♬♩",	input_text: "♪♫♬♩"},	
{label: "♠♥♣♦", input_text: "♠♥♣♦"},	
]);

var SPE3 = PageMenu({
	label: "特殊字符",
	condition: "input",
	insertBefore: "spe-charaters",
});
SPE3([
{label: "©®™",	input_text: "©®™"},
{label: "のあぃ",	input_text: "のあぃ"},
{label: "•",	input_text: "•"},
{label: "×÷",	input_text: "×÷"},
{label: "≠≈",	input_text: "≠≈"},
{label: "↑↓",	input_text: "↑↓"},
{label: "←→",	input_text: "←→"},
{label: "»«",	input_text: "»«"},
{label: "「」",	input_text: "「」"},
{label: "『』",	input_text: "『』"},
{label: "℃℉",	input_text: "℃℉"},
]);





//================菜单栏的“工具”菜单================
menu = ToolMenu({
    label: "切换火狐配置",
    id:"ProfileSwitch",
    image: ""
});
menu([
{
    label: "默认火狐",
    text: "-no-remote -profile ..\\Profiles\\Default",
		exec: Services.dirsvc.get("ProfD", Ci.nsILocalFile).path + "\\..\\..\\Firefox\\firefox.exe",
},
{
    label: "我的配置",
    text: "-no-remote -profile ..\\Profiles\\MyFirefox",
		exec: Services.dirsvc.get("ProfD", Ci.nsILocalFile).path + "\\..\\..\\Firefox\\firefox.exe",
},
{
    label: "其他配置",
    text: "-no-remote -profile ..\\Profiles\\Other",
		exec: Services.dirsvc.get("ProfD", Ci.nsILocalFile).path + "\\..\\..\\Firefox\\firefox.exe",
},{
    label:"配置备份",
    image: "",
    tooltiptext: "备份文件将另存为桌面，备份文件包含个人隐私，请妥善保管",
		onclick: function(){
	var file = Services.dirsvc.get('UChrm', Ci.nsILocalFile);
	file.appendRelativePath("Local\\BackupProfiles.bat");
	file.launch(); return file;
		}}
]);


//================标签右键菜单-================
tab([//添加标签右键菜单项
 	
{
label : "复制当前标签",
id:"context_CopyTab",
insertAfter:"context_pinTab",
image:"",
onclick :  function() {var oldHistory = gBrowser.webNavigation.sessionHistory;
gBrowser.selectedTab = gBrowser.addTab("about:blank");
var newHistory = gBrowser.webNavigation.sessionHistory;
newHistory.QueryInterface(Components.interfaces.nsISHistoryInternal);
for (var i = 0; i < oldHistory.count; i++) { newHistory.addEntry(oldHistory.getEntryAtIndex(i, false), true); }
if(oldHistory.count) gBrowser.webNavigation.gotoIndex(oldHistory.index);}
},

{
		label:"重新载入标签",
    id:"context_ReloadTabandAllTab",
		image:"",
    tooltiptext: "左键：重新载入标签\n右键：重新载入所有标签",
    onclick: function(e) {
                switch(e.button) {
            case 0:
            gBrowser.reloadTab(TabContextMenu.contextTab);
            break;
						case 1:
				
						break;
            case 2:
            gBrowser.reloadAllTabs();
            break;
                }
        }
	},
{
   id:"BookmarkAllTabToUnfiled",
    label: "所有标签存为书签",
    image:"",
    tooltiptext: "不包括空白页",
    oncommand: function() {
        function getDateTime() {
            var now = new Date();
            return now.toLocaleFormat("%m-%d %H:%M");
        }
        XULBrowserWindow.statusTextField.label = "所有标签存为书签 " + getDateTime();

        var is_folder_exit = 0;
        var browsers = document.getElementById('content').browsers;
        for (var n = 0; n < browsers.length; ++n) {
            var webNav = browsers[n].webNavigation;
            var url = webNav.currentURI.spec;
            var name = "";
            try {
                var doc = webNav.document;
                [/\s(·|::|-|—|»|\|)\s.*/i, /_[^\[\]【】]+$/].forEach(function(r) {
                    doc.title = doc.title.replace(r, "");
                }); //简化标题
                name = doc.title || url;
            } catch (e) {
                name = url;
            }
            if (name != "about:blank") {
                if (is_folder_exit == 0) {
                    var bookmarksService = Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"].getService(Components.interfaces.nsINavBookmarksService);
                    //var target_folder = bookmarksService.bookmarksMenuFolder; //书签菜单
                    //var target_folder = bookmarksService.toolbarFolder; //书签工具列
                    var target_folder = bookmarksService.unfiledBookmarksFolder; //未排序书签
                    target_folder = bookmarksService.createFolder(target_folder, getDateTime(), 0);
                    is_folder_exit = 1;
                }
                bookmarksService.insertBookmark(target_folder, webNav.currentURI, -1, name);
            }
        }
    }
},
{
id:"SaveAllTabImages",
    label: "保存当前所有图片",
    oncommand: function() {
        // 保存ディレクトリのパスがない场合は毎回ダイアログで决める
        //var path = "C:\\Users\\azu\\Downloads"; // エスケープしたディレクトリのパス
        var path = "";
        if (!path) {
            // ファイル保存ダイアログ
            var nsIFilePicker = Ci.nsIFilePicker;
            var FP = Cc['@mozilla.org/filepicker;1'].createInstance(nsIFilePicker);
            FP.init(window, 'Choose save folder.', nsIFilePicker.modeGetFolder);

            // ダイアログ表示
            if (FP.show() == nsIFilePicker.returnOK) {
                path = FP.file.path;
            } else {
                return false;
            }
        }
        // ダウンロードしたページを表示するために URI オブジェクト生成
        var hostURL = Components.classes['@mozilla.org/network/io-service;1'].getService(Components.interfaces.nsIIOService).newURI(location.href, null, null);
        // ページに贴り付けられた画像を保存する
        var links = content.document.images;
        var pack = [];
        for (var i = 0, length = links.length; i < length; i++) {
            // JPEG と PNG を保存する
            if (links[i].src.match(/\.jpe?g|\.png|\.php|\.bmp|\.gif|img\.blogs\.yahoo(.*)folder[^thumb]/i)) {
                pack.push([links[i].src.split("/").pop(), links[i].src]);
            }
        }
        zipDeKure(pack, path);


        function zipDeKure(urls, savePath) {
            const ioService = Cc["@mozilla.org/network/io-service;1"].getService(Ci.nsIIOService);
            const zipWriter = Components.Constructor("@mozilla.org/zipwriter;1", "nsIZipWriter");
            var uri = content.window.location.href;
            var fileName = uri.substring(uri.lastIndexOf('://') + 3, uri.length);
            fileName = fileName.split(".").join("_");
            fileName = fileName.split("/").join("_");
            fileName = fileName.split("?").join("_");
            var path = savePath + "\\" + fileName + ".zip";
            var file = Cc["@mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
            file.initWithPath(path);
            var zipW = new zipWriter();
            var ioFlag = 0x04 | 0x08 | 0x20;
            zipW.open(file, ioFlag);
            for (var i = 0, len = urls.length; i < len; i++) {
                var [name, url] = urls[i];
                var ch = ioService.newChannel(url, "UTF-8", null);
                var stream = ch.open();
                zipW.addEntryStream(name, Date.now() * 1000, Ci.nsIZipWriter.COMPRESS_DEFAULT, stream, false);
            }
            zipW.close();
        }
    },
    image: ""
}
]);




new function () {
	var items = [
{
		label: "关闭右侧标签",
    id:"context_closeTabsToTheLast",
    oncommand:  function() {var tabs = gBrowser.mTabContainer.childNodes; for (var i = tabs.length - 1; tabs[i] != gBrowser.selectedTab; i--) { gBrowser.removeTab(tabs[i]);}},
	 image:""
	},
    {
		label: "关闭左侧标签",
    id:"context_closeTabsToTheFirst",
		image:"",
		oncommand: function() {var tabs = gBrowser.mTabContainer.childNodes,i; for (i = 0; tabs[i] != gBrowser.selectedTab; i++);	for (i--;i>=0;i--){gBrowser.removeTab(tabs[i]);}}},
{
		label: "关闭其他标签",
    id:"context_removeAllTabsButCurrent",
		oncommand: "gBrowser.removeAllTabsBut(TabContextMenu.contextTab);",
 	image:"",
	},
{
		label: "关闭所有标签",
    id:"context_closeAllTabs",
		oncommand: "gBrowser.removeAllTabsBut(gBrowser.addTab('about::superstart'));",
 	image:"",
	},
{
label : "关闭重复标签",
id:"context_CloseSameTab",
 	image:"",
oncommand : function () {
	var num = gBrowser.browsers.length;
	var msg = "";
	for (var i = 0; i < num; i++)
	{
		var a = gBrowser.getBrowserAtIndex(i);
		try
		{
			for (var j = 0; j < num; j++)
			{
				if (j != i)
				{
					var b = gBrowser.getBrowserAtIndex(j);
					if (a.currentURI.spec == b.currentURI.spec)
					{
						//gBrowser.alert(a.currentURI.spec);
						if (msg != "")
							msg += "\n";
						msg += b.currentURI.spec;
						gBrowser.removeTab(gBrowser.tabContainer.childNodes[j]);
						num--;
						j--;
						//Not executing "i--" because there won't be tabs equal before the one on i
					}
				}
			}
		}
		catch(e)
		{
			Components.utils.reportError(e);
		}
	}
	if (msg != ""){
		//alert("\u5173\u95ED\u7684\u91CD\u590D\u6807\u7B7E\u9875:\n\n" + msg);
		}
	else
		alert("\u6CA1\u6709\u91CD\u590D\u6807\u7B7E\u9875");
},
},
	];
	var menu = TabMenu({id:"context_CloseTab", onpopupshowing: syncHidden});
	menu(items);
};







new function () {
	var items = [
    {label:"复制当前标签标题",oncommand: function() {addMenu.copy(addMenu.convertText("%TITLES%"));},image:""},
	{label:"复制当前标签地址",oncommand: function() {addMenu.copy(addMenu.convertText("%URL%"));},image:""},
	{label:"复制当前标签标题和地址",oncommand: function() {addMenu.copy(addMenu.convertText("%TITLES%\n%URL%"));},image:""},
	{label:"复制当前标签源代码",oncommand: function() {addMenu.copy(addMenu.convertText( '<a href="%URL%" target="_blank">%TITLES%</a>'));},image:""},
{},
	{label:"复制所有标签标题",oncommand: function() {(function(){
           var titles = "";
            Array.slice(gBrowser.tabContainer.childNodes).forEach(function(tab) {
                titles += tab.label + "\n";
            });
            this.clipboard.copyString(titles);   
    })();},image:""},
	{label:"复制所有标签地址",oncommand: function() {(function(){
            var URLs = "";
            Array.slice(gBrowser.tabContainer.childNodes).forEach(function(tab) {
                var url = gBrowser.getBrowserForTab(tab).contentWindow.location.href;
                URLs += url + "\n";
            });
            this.clipboard.copyString(URLs);      
    })();},image:""},
	{label:"复制所有标签标题和地址",oncommand: function() {(function() {
            var txt = "";
            Array.slice(gBrowser.tabContainer.childNodes).forEach(function(tab) {
                 var url = gBrowser.getBrowserForTab(tab).contentWindow.location.href;
                txt += tab.label + "\n" + url + "\n";
            });
            this.clipboard.copyString(txt); 
        })();},image:""},
{label:"复制所有标签标源代码",oncommand: function() {(function() {
            var txt = "";
            Array.slice(gBrowser.tabContainer.childNodes).forEach(function(tab) {
                 var url = gBrowser.getBrowserForTab(tab).contentWindow.location.href;
                txt += "<a href=" + "\""+ url +"\" "+  "target=\"_blank\">" +  tab.label + "</a>"+ "<br>"+ "\r";
            });
            this.clipboard.copyString(txt); 
        })();},image:""},

	];
	var menu = TabMenu({id:"context_TabInfoCopy",onpopupshowing: syncHidden});
	menu(items);
};



//隐藏相同项。必须，不能删除
function syncHidden(event) {
	Array.slice(event.target.children).forEach(function(elem){
		var command = elem.getAttribute('command');
		if (!command) return;
		var original = document.getElementById(command);
		if (!original) {
				elem.hidden = true;
				return;
		};
		elem.hidden = original.hidden;
		elem.collapsed = original.collapsed;
		elem.disabled = original.disabled;
	});
};


